# coding=utf-8
# python编程作业：图书管理系统
import json
import os

books = []


# 菜单函数，输出打印信息，接收用户输入
def menu():
    print("*****************************")
    print("*      图书管理系统           *")
    print("* 1. 添加新图书信息           *")
    print("* 2. 通过图书ID修改图书信息      *")
    print("* 3. 通过图书ID删除图书信息      *")
    print("* 4. 通过书名删除图书信息      *")
    print("* 5. 通过图书ID查询图书信息      *")
    print("* 6. 通过书名查询图书信息      *")
    print("* 7. 显示所有图书信息         *")
    print("* 8. 退出系统                *")
    print("*****************************")
    select_num = input("请输入你的选择：")
    return select_num


# 书的ID
def getID():
    id = input("请输入图书ID：")
    return id


# 书名
def getName():
    name = input("请输入图书名称：")
    return name


# 价格
def getPrice():
    while True:
        price = input("请输入图书价格：")
        if price.isdigit():  # 判断输入的是否是纯数字
            return int(price)
        else:
            print("价格输入错误，请重新输入")


# 图书简介
def getSummary():
    summary = input("请输入图书简介：")
    return summary


# 添加图书
def addBook(id, name, price, summary):
    book_dit = {}
    for book in books:
        if book["id"] == id:
            print("图书的ID已存在，添加图书失败")
            return "图书添加失败"
    else:
        book_dit["id"] = id
        book_dit["name"] = name
        book_dit["price"] = price
        book_dit["summary"] = summary
        books.append(book_dit)
        print("图书添加成功", book_dit)
        return "图书添加成功"


# 根据id修改图书
def modifyBookByID(id):
    for book in books:
        if book["id"] == id:
            name = getName()
            price = getPrice()
            summary = getSummary()
            book["name"] = name
            book["price"] = price
            book["summary"] = summary
            print("图书修改成功")
            return "图书修改成功"
    else:
        print(f"图书id{id}不存在,修改失败")
        return "图书修改失败"


# 根据id删除图书
def deleteBookByID(id):
    for book in books:
        if book["id"] == id:
            books.remove(book)
            print("图书删除成功")
            return "图书删除成功"
    else:
        print(f"图书id{id}不存在,删除失败")
        return "图书删除失败"


# 根据书名删除图书
def deleteBookByName(name):
    del_book = []
    for book in books:
        if book["name"] == name:
            del_book.append(book)
    if len(del_book) > 0:
        for book in del_book:
            books.remove(book)
            print(f"书名为{book['name']}的图书删除成功")
        return "删除图书成功"
    else:
        print(f"书名为{name}的图书不存在，删除图书失败")
        return "删除图书失败"


# 通过id查询图书
def queryBookByID(id):
    for book in books:
        if book["id"] == id:
            print("根据id查询图书成功", book)
            return "根据id查询图书成功"
    else:
        print("根据id图书查询失败")
        return f"根据id查询图书失败,没有id为{id}的图书"


# 根据书名查询图书
def queryBookByName(name):
    sucess = False
    for book in books:
        if book["name"] == name:
            print("根据书名查询图书成功", book)
            sucess = True
    if sucess:
        return f"根据书名查询图书成功"
    else:
        print("根据id图书查询失败")
        return f"根据书名查询图书失败,没有书名为{name}的图书"


# 显示所有图书信息
def showAllInfo():
    for book in books:
        print(book)
    return "图书显示成功"


# 图书系统业务管理
def bookManager():
    while True:
        select_num = menu()
        if len(select_num) == 1 and select_num in "12345678":
            if select_num == "1":
                id = getID()
                name = getName()
                price = getPrice()
                summary = getSummary()
                addBook(id, name, price, summary)
            elif select_num == "2":
                id = getID()
                modifyBookByID(id)
            elif select_num == "3":
                id = getID()
                deleteBookByID(id)
            elif select_num == "4":
                name = getName()
                deleteBookByName(name)
            elif select_num == "5":
                id = getID()
                queryBookByID(id)
            elif select_num == "6":
                name = getName()
                queryBookByName(name)
            elif select_num == "7":
                showAllInfo()
            elif select_num == "8":
                break
        else:
            print("请输入正确的选择：")


if __name__ == '__main__':

    try:
        # 先读取数据,如果文本没有数据，则返回个空列表
        with open("text.txt", "r", encoding='utf-8') as f:
            res_str = f.readline()
            res_list = json.loads(res_str)
            books = res_list
    except:
        books = []

    bookManager()

    # 程序执行完，再写入数据，覆盖之前的数据，重新写入
    with open('text.txt', "w", encoding='utf-8') as f:
        f.write(json.dumps(books))
